package my.ywarn;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import my.guojian.jdbc.util.DbConUtil;
import my.guojian.jdbc.util.JdbcTemplate;

public class Ywarn {

	private static final Log log = LogFactory.getLog(Ywarn.class);
	private JFrame frame;
	private JScrollPane jscrollPane;
	private JTextArea jtextArea;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Ywarn window = new Ywarn();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Ywarn() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("数据同步");
		frame.setBounds(100, 100, 623, 390);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new BorderLayout(0, 0));

		jtextArea = new JTextArea();

		jscrollPane = new JScrollPane(jtextArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		frame.getContentPane().add(jscrollPane);

		beginTask();

	}

	private void beginTask() {

		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.scheduleAtFixedRate(new Runnable() {
			public void run() {
				jtextArea.append(DateFormatUtils.format(Calendar.getInstance().getTime(), "yyyy-MM-dd HH:mm:ss") + "====>成功更新" + updateYwWarn() + "条数据.\n");
				jtextArea.setCaretPosition(jtextArea.getText().length());
				if (jtextArea.getLineCount() > 100) {
					jtextArea.setText("");
				}
			}
		}, 0, 2, TimeUnit.MINUTES);
	}

	private String updateYwWarn() {
		log.info("===================开始执行数据更新===================");
		String counts = "0";
		try {
			File file = new File("c:/更新时间记录.txt");
			if (!file.exists()) {
				file.createNewFile();
			}

			String nowTime = FileUtils.readFileToString(file);

			if (StringUtils.isBlank(nowTime)) {
				System.exit(0);
				return counts;
			}

			String[] result = ywWarn(nowTime);
			String lastTime = result[0];
			counts = result[1];

			log.info("数据库中 last time: " + lastTime);

			if (StringUtils.isNotBlank(lastTime)) {
				FileUtils.writeStringToFile(file, lastTime);
			}

		} catch (IOException e1) {
			e1.printStackTrace();
			log.error(e1);
		}
		return counts;
	}

	private static String[] ywWarn(String nowTime) {
		String warnSql = " SELECT * FROM T_SIGNALSYSINFO102116  WHERE CRTTIME > '" + nowTime + "' ORDER BY CRTTIME asc ";
		List<Object[]> warnInfoList = JdbcTemplate.queryListFieldInfoByFields(DbConUtil.getConnectionBean("warno"), warnSql, null);

		String lastTime = "";
		int i = 0;
		for (Object[] objects : warnInfoList) {
			int warnLevel = getWarnLevel(objects[0] + "");
			String area = objects[3] + "";
			String sender = getSender(objects[12] + "");
			String sendtime = objects[8] + "";
			String content = objects[12] + "";
			String title = getTitle(sender, objects[6] + "", objects[9] + "", (objects[0] + "").trim());

			Object[] eventType = JdbcTemplate.queryFieldInfoByFields(DbConUtil.getConnectionBean("warns"),
					"SELECT * FROM eventType WHERE eventTypeName like '%" + objects[9] + "" + "%'", null);
			String eventTypeCode = eventType[2] + "";

			String recodeTime = objects[2] + "";
			String sql = " INSERT INTO Warn(warnLevel,Area,Sender,sendtime,content,title,eventTypeCode,RecordTime,Readed) " + "VALUES ( " + warnLevel + ", '" + area + "', '"
					+ sender + "', '" + sendtime + "','" + content + "', '" + title + "', '" + eventTypeCode + "', '" + recodeTime + "', 0); ";

			log.info("--正在插入第" + ++i + "条数据");
			JdbcTemplate.updateByFields(DbConUtil.getConnectionBean("warns"), sql, null);
			lastTime = objects[2] + "";
		}
		return new String[] { lastTime.trim(), i + "" };
	}

	private static String getTitle(String sender, String issState, String type, String color) {
		StringBuffer sb = new StringBuffer();
		sb.append(sender + issState + type + color + "预警");
		return sb.toString();
	}

	private static String getSender(String content) {
		String sender = "";
		if (content.contains("市规划和国土资源委员会")) {
			sender = "深圳市规划和国土资源委员会深圳市气象局";
		} else if (content.contains("市气象台")) {
			sender = "深圳市气象台";
		}
		return sender;
	}

	private static int getWarnLevel(String color) {
		color = color.trim();
		int warnLevel = 5;
		if (color.equals("红色")) {
			warnLevel = 1;
		} else if (color.equals("橙色")) {
			warnLevel = 2;
		} else if (color.equals("黄色")) {
			warnLevel = 3;
		} else if (color.equals("蓝色")) {
			warnLevel = 4;
		}
		return warnLevel;
	}
}
